package com.neighbor.neighborhooduser.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.neighbor.neighborhooduser.pojo.ItemOrders;
import com.neighbor.neighborhooduser.pojo.OrderWithItemDTO;
import com.neighbor.neighborhooduser.service.IItemOrdersService;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import java.util.UUID;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/**
 * <p>
 * 物品交易订单表 前端控制器
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */

@RestController
@RequestMapping("/itemOrders")
public class ItemOrdersController {
    @Autowired
    private IItemOrdersService iItemOrdersService;
    @Autowired
    private IItemOrdersService itemOrdersService;
    //生成订单
    @RequestMapping("/createOrders")
    ResponseMsg createOrders(@RequestBody ItemOrders order){
        String orderNumber = UUID.randomUUID().toString().replace("-", "");
        System.out.println("订单号："+orderNumber);
        order.setOrderNumber(orderNumber);
        iItemOrdersService.createOrder(order);
        ItemOrders orders = iItemOrdersService.getByOrderNumber(orderNumber);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,orders);
    }
    @RequestMapping("/getById")
    ResponseMsg getById(@RequestParam Integer orderId){
        ItemOrders orders = iItemOrdersService.getById(orderId);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,orders);
    }
    //修改订单状态为已支付
    @RequestMapping("/updateStaus")
    ResponseMsg updateStatus(@RequestParam Integer orderId){
        if(iItemOrdersService.updateStatus(orderId)==1){
            return ResponseMsg.success();
        }
        return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"错误");
    }
// 在类中添加日志声明
    private static final Logger log = LoggerFactory.getLogger(ItemOrdersController.class);

    /**
     * 根据用户ID和角色获取所有状态的订单
     *
     * 该接口返回包含买卖双方名称和物品标题的完整订单信息
     *
     * @param userId 用户ID
     * @param role 用户角色（seller-卖家，buyer-买家）
     * @return 响应消息对象，包含订单列表
     *
     * @apiNote
     *   - 路径: /getOrders/{userId}/{role}
     *   - 方法: GET
     *   - 示例: GET /getOrders/123/seller
     *
     * @response 成功响应示例:
     * {
     *   "code": 200,
     *   "msg": "成功",
     *   "data": [
     *     {
     *       "id": 1,
     *       "orderNumber": "ORD20230924001",
     *       "sellerId": 123,
     *       "sellerName": "张三",
     *       "buyerId": 456,
     *       "buyerName": "李四",
     *       "itemId": 789,
     *       "itemTitle": "iPhone 13 Pro Max",
     *       "totalAmount": 8999.00,
     *       "status": 2,
     *       "statusDesc": "进行中",
     *       "createTime": "2023-09-24T10:30:00"
     *     },
     *     // ...其他订单
     *   ]
     * }
     *
     * @response 错误响应示例:
     * {
     *   "code": 403,
     *   "msg": "无效角色",
     *   "data": null
     * }
     */

    @RequestMapping("getOrders/{userId}/{role}")
    public ResponseMsg getOrdersById(
            @PathVariable Integer userId,
            @PathVariable String role) {

        try {
            log.info("获取订单列表 [用户ID:{}] [角色:{}]", userId, role);

            // 1. 验证角色权限
            if (!"seller".equalsIgnoreCase(role) && !"buyer".equalsIgnoreCase(role)) {
                log.warn("无效角色 [用户ID:{}] [角色:{}]", userId, role);
                return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR,
                        "无效角色，仅支持'seller'或'buyer'", null);
            }

            // 2. 查询订单数据
            List<OrderWithItemDTO> orders;

            if ("seller".equalsIgnoreCase(role)) {
                // 查询卖家订单
                orders = itemOrdersService.findSellerOrdersWithDetails(userId);
            } else {
                // 查询买家订单
                orders = itemOrdersService.findBuyerOrdersWithDetails(userId);
            }

            log.debug("查询结果 [数量:{}]", orders == null ? 0 : orders.size());

            // 3. 处理查询结果
            if (orders == null || orders.isEmpty()) {
                log.info("未找到订单 [用户ID:{}] [角色:{}]", userId, role);
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS,
                        "未找到相关订单", Collections.emptyList());
            }

            // 4. 返回成功响应
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,
                    "成功获取" + orders.size() + "条订单", orders);
        } catch (Exception e) {
            // 详细记录异常信息
            log.error("获取订单列表异常 [用户ID:{}] [角色:{}]：{}",
                    userId, role, e.toString(), e);

            // 返回更详细的错误信息
            String errorMsg = "查询失败";
            if (e.getMessage() != null) {
                errorMsg += ": " + e.getMessage();
            } else {
                errorMsg += "，异常类型: " + e.getClass().getSimpleName();
            }

            return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR, errorMsg, null);
        }
    }


    /**
     * 根据用户ID、角色和状态获取特定状态的订单
     *
     * 该接口用于查询指定用户（卖家或买家）在特定状态下的订单。
     *
     * @param userId 用户ID
     * @param role 用户角色（seller-卖家，buyer-买家）
     * @param status 订单状态 (1:待确认, 2:进行中, 3:已完成, 4:已取消)
     * @return 响应消息对象，包含订单列表
     *
     * @apiNote
     *   - 路径: /getOrders/{userId}/{role}/{status}
     *   - 方法: GET
     *   - 示例: GET /getOrders/123/seller/2
     *
     * @response 成功响应示例:
     * {
     *   "code": 200,
     *   "msg": "成功获取卖家订单数据",
     *   "data": [
     *     {
     *       订单数据
     *     }
     *   ]
     * }
     *
     * @response 错误响应示例:
     * {
     *   "code": 400,
     *   "msg": "无效的订单状态代码，有效范围：1-4",
     *   "data": null
     * }
     */
    @RequestMapping("getOrders/{userId}/{role}/{status}")
    public ResponseMsg getOrdersByUserAndStatus(@PathVariable Integer userId,
                                                @PathVariable String role,
                                                @PathVariable Byte status) {
        try {
            log.info("获取订单请求 [用户ID:{}] [角色:{}] [状态:{}]", userId, role, status);

            // 1. 验证角色权限
            if (!"seller".equalsIgnoreCase(role) && !"buyer".equalsIgnoreCase(role)) {
                log.warn("无效角色 [用户ID:{}] [角色:{}]", userId, role);
                return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR,
                        "无效角色，仅支持'seller'或'buyer'", null);
            }

            // 2. 验证订单状态有效性
            if (status < 1 || status > 4) {
                log.warn("无效订单状态 [用户ID:{}] [状态:{}]", userId, status);
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,
                        "无效的订单状态代码，有效范围：1-4", null);
            }

            // 3. 根据角色查询订单数据
            List<OrderWithItemDTO> orders;
            String roleDescription;

            if ("seller".equalsIgnoreCase(role)) {
                // 查询卖家订单
                orders = itemOrdersService.findOrdersBySellerAndStatus(userId, status);
                roleDescription = "卖家";
            } else {
                // 查询买家订单
                orders = itemOrdersService.findOrdersByBuyerAndStatus(userId, status);
                roleDescription = "买家";
            }

            log.debug("查询结果 [数量:{}]", orders == null ? 0 : orders.size());

            // 4. 处理查询结果
            if (orders == null || orders.isEmpty()) {
                log.info("未找到匹配订单 [用户ID:{}] [角色:{}] [状态:{}]", userId, role, status);
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS,
                        "未找到" + roleDescription + "的订单记录", Collections.emptyList());
            }

            // 5. 返回成功响应
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,
                    "成功获取" + roleDescription + "订单数据", orders);
        } catch (Exception e) {
            // 详细记录异常信息
            log.error("获取订单异常 [用户ID:{}] [角色:{}] [状态:{}]：{}",
                    userId, role, status, e.toString(), e);

            // 返回更详细的错误信息
            String errorMsg = "服务器内部错误";
            if (e.getMessage() != null) {
                errorMsg += ": " + e.getMessage();
            } else {
                errorMsg += "，异常类型: " + e.getClass().getSimpleName();
            }

            return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR, errorMsg, null);
        }
    }

    /**
     * 根据物品标题模糊查询用户所有相关订单
     *
     * @param userId 用户ID
     * @param encodedTitle URL编码后的物品标题
     * @return 响应消息对象
     *
     * @apiNote
     *   - 路径: /orders/byTitle/{userId}/{encodedTitle}
     *   - 方法: GET
     *   - 示例: GET /orders/byTitle/123/%E6%89%8B%E6%9C%BA
     */
    @RequestMapping("/orders/byTitle/{userId}/{encodedTitle}")
    public ResponseMsg getOrdersByItemTitle(
            @PathVariable Integer userId,
            @PathVariable String encodedTitle) {

        try {

            // 解码 URL 编码的标题
            String title = URLDecoder.decode(encodedTitle, StandardCharsets.UTF_8);


            log.info("根据物品标题查询订单 [用户ID:{}] [标题:{}]", userId, title);

            // 1. 验证标题参数
            if (title == null || title.trim().isEmpty()) {
                log.warn("标题参数为空 [用户ID:{}]", userId);
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,
                        "物品标题不能为空", null);
            }

            // 2. 查询订单数据（包含买家和卖家订单）
            List<OrderWithItemDTO> orders = itemOrdersService.findOrdersByUserIdAndItemTitle(userId, title);

            log.debug("查询结果 [数量:{}]", orders == null ? 0 : orders.size());

            // 3. 处理查询结果
            if (orders == null || orders.isEmpty()) {
                log.info("未找到匹配订单 [用户ID:{}] [标题:{}]", userId, title);
                return ResponseMsg.getInstance(ResponseMsg.SUCCESS,
                        "未找到包含'" + title + "'的订单", Collections.emptyList());
            }

            // 4. 返回成功响应
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,
                    "成功获取" + orders.size() + "条包含'" + title + "'的订单", orders);
        } catch (Exception e) {
            // 详细记录异常信息
            log.error("根据物品标题查询订单异常 [用户ID:{}] [标题:{}]：{}",
                    userId, encodedTitle, e, e);

            // 返回更详细的错误信息
            String errorMsg = "查询失败";
            if (e.getMessage() != null) {
                errorMsg += ": " + e.getMessage();
            } else {
                errorMsg += "，异常类型: " + e.getClass().getSimpleName();
            }

            return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR, errorMsg, null);
        }
    }


    /**
     * 根据订单ID获取完整的订单信息
     *
     * 该接口返回包含买卖双方信息、物品信息和订单详情的完整数据
     *
     * @param orderId 订单ID
     * @return 响应消息对象，包含订单详情
     *
     * @apiNote
     *   - 路径: /getOrderById/{orderId}
     *   - 方法: GET
     *   - 示例: GET /getOrderById/123
     *
     * @response 成功响应示例:
     * {
     *   "code": 200,
     *   "msg": "成功获取订单信息",
     *   "data": {
     *     "orderId": 123,
     *     "orderNumber": "ORD20230924001",
     *     "sellerId": 456,
     *     "sellerName": "张三",
     *     "sellerBuilding": "A栋",
     *     "buyerId": 789,
     *     "buyerName": "李四",
     *     "buyerBuilding": "B栋",
     *     "itemId": 101,
     *     "title": "iPhone 13 Pro Max",
     *     "status": 2,
     *     "rentDays": 7,
     *     "startDate": "2023-09-24",
     *     "endDate": "2023-10-01",
     *     "price": 299.00,
     *     "statusDesc": "进行中"
     *   }
     * }
     *
     * @response 错误响应示例:
     * {
     *   "code": 404,
     *   "msg": "未找到订单",
     *   "data": null
     * }
     */
    @RequestMapping("/getOrderById/{orderId}")
    public ResponseMsg getOrderById(@PathVariable Integer orderId) {
        try {
            log.info("获取订单详情 [订单ID:{}]", orderId);

            // 1. 查询订单详情
            OrderWithItemDTO order = itemOrdersService.findOrderDetailsById(orderId);

            // 2. 处理查询结果
            if (order == null) {
                log.warn("未找到订单 [订单ID:{}]", orderId);
                return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,
                        "未找到订单ID为" + orderId + "的记录", null);
            }

            log.debug("订单详情: {}", order);

            // 3. 返回成功响应
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS,
                    "成功获取订单信息", order);
        } catch (Exception e) {
            // 详细记录异常信息
            log.error("获取订单详情异常 [订单ID:{}]：{}", orderId, e.toString(), e);

            // 返回更详细的错误信息
            String errorMsg = "查询失败";
            if (e.getMessage() != null) {
                errorMsg += ": " + e.getMessage();
            } else {
                errorMsg += "，异常类型: " + e.getClass().getSimpleName();
            }

            return ResponseMsg.getInstance(ResponseMsg.REQUEST_ERROR, errorMsg, null);
        }
    }

    //确认收货
    @RequestMapping("/confirmRecover/{orderId}/{status}")
    ResponseMsg alertOrderStatus(@PathVariable Integer orderId, @PathVariable Byte status){
        // 1.判断status是否合格
        if (status < 1 || status > 4){
            return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"未知状态");
        }
        UpdateWrapper<ItemOrders> wrapper = new UpdateWrapper<>();
        wrapper.set("status", 3)
                .eq("order_id", orderId);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "确认收获",
                itemOrdersService.update(wrapper));
    }

    //取消订单
    @RequestMapping("/cancelOrder/{orderId}/{status}")
    ResponseMsg cancelOrder(@PathVariable Integer orderId, @PathVariable Byte status){
        // 1.判断status是否合格
        if (status < 1 || status > 4){
            return ResponseMsg.getInstance(ResponseMsg.DATA_ERROR,"未知状态");
        }
        UpdateWrapper<ItemOrders> wrapper = new UpdateWrapper<>();
        wrapper.set("status", 4)
                .eq("order_id", orderId);
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "确认取消",
                itemOrdersService.update(wrapper));
    }
}
